package com.lepu.app.fun.hospital;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.app.config.UserConfig;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.eyzhs.app.R;
import com.lepu.app.fun.hospital.adapter.HospitalAdviceAdapter;
import com.lepu.app.fun.hospital.bean.HospitalAdvice;
import com.lepu.app.fun.mother_circle.MotherTopicActivity;
import com.lepu.app.fun.mother_circle.bean.BeanMotherCircle;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class HospitalAdviceReportActivity extends BaseFragmentActivity implements AsyncRequest,
		OnRefreshListener, OnLoadListener ,OnTopbarNewLeftLayoutListener {

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;


	// ========================================================================
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private HospitalAdviceAdapter mDataAdapter = null;
	private ArrayList<HospitalAdvice> mDataArrayList = null;
	
	private int mCurrentPage = 1;

	public BeanMotherCircle mMotherCircle = null;

	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hospital_advice_activity);
		init();
	}

	@Override
	public void onDestroy() {
        super.onDestroy();
	}
	
	@Override
	public void onBackPressed() {
		finish(true);
	}
	
	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
		
	}

	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
			{
				noDataLayout.setVisibility(View.VISIBLE);
			}else{
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}
	

	@SuppressWarnings("deprecation")
	@SuppressLint({ "ResourceAsColor", "DefaultLocale" })
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("咨询记录");
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		mDataListView = (ListView) findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
											R.color.color_listview_refresh_2,
											R.color.color_listview_refresh_3,
											R.color.color_listview_refresh_4);
		mDataArrayList = new ArrayList<HospitalAdvice>();
		
		request(false);
	}

	//请求数据
	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
		}

		String url = Setting.getHospitalAdviceListUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
			
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true,false,true);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				
				ArrayList<HospitalAdvice> dataList = (ArrayList<HospitalAdvice>) msg.obj;
				if (dataList != null && dataList.size() > 0) {
					showHideNoDataLayout(false);
					mDataArrayList = dataList;
					
					correctCount(mDataArrayList);
					
					mDataAdapter = new HospitalAdviceAdapter(HospitalAdviceReportActivity.this,mDataArrayList);
					mDataListView.setAdapter(mDataAdapter);
					
				} else {
                    showHideNoDataLayout(true);
					
				}

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				showHideNoDataLayout(true);
				break;
			case MSG_DATA_MORE_SUCCESS:

				ArrayList<HospitalAdvice> dataMoreList = (ArrayList<HospitalAdvice>) msg.obj;
				
				if (dataMoreList != null && dataMoreList.size() > 0) {
					
				    mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(MotherTopicActivity.getInstance(), R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;

			default:
				break;
			}
		};
	};

	//矫正总数
	public void correctCount(ArrayList<HospitalAdvice> dataList){
		int totalCount = 0;
		int allCount = Integer.valueOf(UserConfig.getConfigString(HospitalAdviceReportActivity.this, "NewCount", "0"));
		
		for(int i=0; i<dataList.size(); i++){
			HospitalAdvice item = dataList.get(i);
			totalCount = totalCount + Integer.valueOf(UserConfig.getConfigString(HospitalAdviceReportActivity.this, "NewCount_"+item.DCQID, "0"));
		}
		
		if(allCount != totalCount){
			allCount = totalCount;
			UserConfig.setConfig(HospitalAdviceReportActivity.this, "NewCount", String.valueOf(allCount));
		}
	}
	
	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		request(false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			ArrayList<HospitalAdvice> dataArraylist = HospitalAdvice.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			ArrayList<HospitalAdvice> dataMoreArraylist = HospitalAdvice.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				
			   mDataArrayList.addAll(dataMoreArraylist);
				
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} 
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		} 
	}





}
